package cn.minhx.mw.dtp.admin.trigger;

import cn.minhx.mw.dtp.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.minhx.mw.dtp.sdk.domain.model.valobj.RegistryEnumVO;
import cn.minhx.mw.dtp.admin.types.Response;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RList;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/dynamic/thread/pool/")
public class DynamicThreadPoolController {

    @Resource
    private RedissonClient redissonClient;

    @RequestMapping(value = "query_thread_pool_list", method = RequestMethod.GET)
    public Response<List<ThreadPoolConfigEntity>> queryThreadPoolList() {
        try {
            RList<ThreadPoolConfigEntity> cacheList = redissonClient.getList(RegistryEnumVO.DTP_THREAD_POOL_CONFIG_LIST.getKey());
            return Response.success(cacheList);
        } catch (Exception e) {
            log.error("查询线程池数据异常", e);
            return Response.error();
        }
    }

    @RequestMapping(value = "query_thread_pool_config", method = RequestMethod.GET)
    public Response<ThreadPoolConfigEntity> queryThreadPoolConfig(@RequestParam String appName, @RequestParam String threadPoolName) {
        try {
            String cacheKey = RegistryEnumVO.DTP_THREAD_POOL_CONFIG.getKey() + "_" + appName + "_" + threadPoolName;
            ThreadPoolConfigEntity threadPoolConfigEntity = redissonClient.<ThreadPoolConfigEntity>getBucket(cacheKey).get();
            return Response.success(threadPoolConfigEntity);
        } catch (Exception e) {
            log.error("查询线程池配置异常", e);
            return Response.error();
        }
    }

    @RequestMapping(value = "update_thread_pool_config", method = RequestMethod.POST)
    public Response<Boolean> updateThreadPoolConfig(@RequestBody ThreadPoolConfigEntity request) {
        try {
            log.info("修改线程池配置开始 {} {} {}", request.getAppName(), request.getThreadPoolName(), JSON.toJSONString(request));
            RTopic topic = redissonClient.getTopic(RegistryEnumVO.DTP_THREAD_POOL_CONFIG_PUBSUB_TOPIC.getKey() + "_" + request.getAppName());
            topic.publish(request);
            log.info("修改线程池配置完成 {} {}", request.getAppName(), request.getThreadPoolName());
            return Response.success(true);
        } catch (Exception e) {
            log.error("修改线程池配置异常 {}", JSON.toJSONString(request), e);
            return Response.error();
        }
    }

}